// pages/reportquery/reportquery.ts
import api from "../../utils/api"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageCode: false as boolean,//是否展示图形验证码
    time: 60 as number,//倒计时
    isSend: false as boolean,//是否已经发送验证码
    phone: "" as string,
    smsCode:'' as string,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },
  showImageCode(): void {
    let mobilePattern = /^1[3-9]\d{9}$/;
    if (this.data.isSend) {
      return;
    }
    if(mobilePattern.test(this.data.phone)) {
      this.setData({
        imageCode: true
      })
    }else {
      wx.showToast({
        title:"手机号格式错误",
        icon:"error"
      })
    }
  },
  checkImageCode(e:any): void {
    const params = {
      phone: this.data.phone,
      imageKey: e.detail.validateImageKey,
      imageValue: e.detail.code
    }
    // 检验验证码
    api.report.sendQueryReportSms(params).then(res => {
      if(res.data.code == '000') {
        // 倒计时,关闭弹窗,发送手机验证码
        this.countDown();
        this.closeImageCode();
        this.setData({
          isSend: true,
        })
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  closeImageCode(): void {
    this.setData({
      imageCode: false
    })
  },
   // 倒计时
   countDown(): void {
    let countdown = this.data.time;
    const timer = setInterval(() => {
      countdown--;
      this.setData({
        time: countdown
      });

      if (countdown === 0) {
        clearInterval(timer);
        this.setData({
          isSend: false,
          time: 60
        });
      }
    }, 1000);
  },
  // 输入手机号
  handlePhone(e:any): void {
    this.setData({
      phone: e.detail.value
    })
  },
  // 验证手机验证码
  checkSms(): void{
    const {phone, smsCode} = this.data
    if(!phone || !smsCode) {
      wx.showToast({
        title: "请检查输入",
        icon:"error"
      })
      return
    }
    const params = {
      phone,
      smsCode
    }
    api.report.checkQueryReportSms(params).then(res => {
      if(res.data.code) {
        wx.navigateTo({
          url:"/pages/reportperson/reportperson?phone=" + phone
        })
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  // 输入手机验证码
  handleCode(e:any): void {
    this.setData({
      smsCode: e.detail.value
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})